﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.IO.Compression;
using NSEEOD_downloader.Tasks;
using System.Diagnostics;

namespace NSEEOD_downloader
{
    public partial class FormDownload : Form
    {
        public string DownloadLink;
        public string DataDir;
        
        public DownloadTask CurrentTask = null;        

        public FormDownload()
        {
            InitializeComponent();
        }

        private void FormDownload_Load(object sender, EventArgs e)
        {
            Debug.Assert(null != CurrentTask);
            CurrentTask.DownloadDir = DataDir;
            CurrentTask.OnComplete += new EventHandler(currentTask_OnComplete);
            CurrentTask.OnNewMessage += new EventHandler(currentTask_OnNewMessage);            
        }

        void currentTask_OnNewMessage(object sender, EventArgs e)
        {
            string Message = "";
            if (null != sender)
            {
                Message = sender.ToString();
            }

            if (lsStatus.Items.Count >= 200)
            {
                lsStatus.Items.Clear();
            }

            ListViewItem item = new ListViewItem(Message);
            lsStatus.Items.Add(item);
            item.EnsureVisible();
            item.Selected = true;
        }

        void currentTask_OnComplete(object sender, EventArgs e)
        {
            calFrom.Enabled = true;
            calTo.Enabled = true;
            btnDownload.Text = "Download";
        }

        protected override void OnClosing(CancelEventArgs e)
        {
            base.OnClosing(e);
            CurrentTask.CancelAsync();
        }

        private void btnDownload_Click(object sender, EventArgs e)
        {
            if (btnDownload.Text == "Stop")
            {
                CurrentTask.CancelAsync();                
            }
            else
            {
                btnDownload.Text = "Stop";
                calFrom.Enabled = false;
                calTo.Enabled = false;                
                CurrentTask.Download(calFrom.SelectionStart, calTo.SelectionStart);
            }
        }
    }
}
